package com.jt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.annotation.CacheFind;
import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;
import com.jt.service.ItemCatService;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.EasyUITree;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCatServiceImpl implements ItemCatService {

    @Autowired
    private ItemCatMapper itemCatMapper;
    @Autowired(required = false)
    private Jedis jedis;

    @Override
    @CacheFind(key = "ITEM_CAT")
    public ItemCat queryItemName(Long itemCatId) {
        ItemCat itemCat = itemCatMapper.selectById(itemCatId);
        return itemCat;
    }

    //商品分类树形展现
    @Override
    @CacheFind(key = "ITEM_CAT_PARENT",seconds = 7*24*60*60)
    public List<EasyUITree> findItemCatList(Long parentId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parent_id", parentId);
        List<ItemCat> itemCatList = itemCatMapper.selectList(wrapper);
        List<EasyUITree> list = new ArrayList<>();
        for (int i = 0; i < itemCatList.size(); i++) {
            ItemCat itemCat = itemCatList.get(i);
            EasyUITree easyUITree = new EasyUITree();
            easyUITree.setId(itemCat.getId());
            easyUITree.setText(itemCat.getName());
            easyUITree.setState(itemCat.getIsParent()?"closed":"open");
            list.add(easyUITree);
        }
        return list;
    }

    /**
     * 实现步骤:
     *      1.先定义key  ITEM_CAT_PARENT::0
     *      2.先查询缓存
     *          有 true  获取缓存数据之后，将json转化为对象后返回
     *          没有 false 应该查询数据库，之后将数据保存到redis中，默认30天超时
     * @param parentId
     * @return
     */
    //商品分类树形展现(缓存)
    @Override
    public List<EasyUITree> findItemCatCache(Long parentId) {
        List<EasyUITree> treeList =new ArrayList<>();
        //定义key,  (::等价于_)
        String key="ITEM_CAT_PARENT::"+parentId;
        //从缓存中获取对象
        if(jedis.exists(key)){
            //存在，直接获取缓存数据
            String json=jedis.get(key);
            treeList=ObjectMapperUtil.toObject(json, treeList.getClass());
        }else {
            //不存在，查询数据库
            treeList = findItemCatList(parentId);
            String json= ObjectMapperUtil.toJSON(treeList);
            jedis.setex(key, 7*24*60*60, json);
        }
        return treeList;
    }
}
